package net.wsfcp.android.ui.view.my.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import net.wsfcp.android.R;
import net.wsfcp.android.base.BaseActivity;
import net.wsfcp.android.bean.requestbean.ReqUpdateUserBean;
import net.wsfcp.android.bean.resultbean.QiniuUploadImageBean;
import net.wsfcp.android.bean.resultbean.UserBean;
import net.wsfcp.android.event.LoginEvent;
import net.wsfcp.android.greendao.utils.UserBeanUtil;
import net.wsfcp.android.http.UrlHelper;
import net.wsfcp.android.http.mvp.contract.InfoContract;
import net.wsfcp.android.http.mvp.presenter.InfoPresenter;
import net.wsfcp.android.ui.widget.CameraAlbumPopwindow;
import net.wsfcp.android.utils.CommonUtils;
import net.wsfcp.android.utils.CommonValue;
import net.wsfcp.android.utils.PhotoUtils;
import net.wsfcp.android.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;

//修改个人信息
public class InfoActivity extends BaseActivity<InfoPresenter> implements InfoContract.InfoView {

    @BindView(R.id.rl_left)
    RelativeLayout rlLeft;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.btn_right)
    Button btnRight;

    @BindView(R.id.txt_username)
    TextView txtUsername;
    @BindView(R.id.edt_phone)
    EditText edtPhone;
    @BindView(R.id.edt_mail)
    EditText edtMail;
    @BindView(R.id.edt_qq)
    EditText edtQq;
    @BindView(R.id.edt_nickname)
    EditText edtNickname;
    @BindView(R.id.edt_realname)
    EditText edtRealName;
    @BindView(R.id.edt_occupy)
    EditText edtOccupy;
    @BindView(R.id.edt_companyname)
    EditText edtCompanyName;
    @BindView(R.id.edt_companytype)
    EditText edtCompanyType;
    @BindView(R.id.edt_address)
    EditText edtAddress;
    @BindView(R.id.edt_fax)
    EditText edtFax;
    @BindView(R.id.edt_zipcode)
    EditText edtZipCode;
    @BindView(R.id.img_sethead)
    ImageView imgSetHead;


    @BindView(R.id.txt_upload_headimg)
    TextView txtUploadHeadImg;
    @BindView(R.id.txt_delete_headimg)
    TextView txt_delete_headimg;
    @BindView(R.id.txt_save)
    TextView txt_save;

    @BindView(R.id.ll_back)
    LinearLayout ll_back;


    @BindView(R.id.rg_group)
    RadioGroup rg;


    private File fileUri;
    private File fileCropUri;
    private Uri imageUri;
    private Uri cropImageUri;

    private String qiNiuPicName = "";
    private String qiNiuPicUrl = "";
    private int gender = 1;//性别  0:女 1:男


    CameraAlbumPopwindow popwindow;

    ReqUpdateUserBean reqUserBean = new ReqUpdateUserBean();

    UserBean userBean = new UserBean();

    UserBeanUtil userBeanUtil;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_info;
    }

    @Override
    protected InfoPresenter loadPresenter() {
        return new InfoPresenter();
    }

    @Override
    protected void initData() {
        setmTitle(getString(R.string.fragment_my_info));
        setLeftClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        txtUsername.setText(SpUtils.getInstance().getUserName());

        initValue();

    }

    public void initValue() {
        userBeanUtil = new UserBeanUtil(this);
        userBean = userBeanUtil.getUserInfo(SpUtils.getInstance().getUserId());
        if (userBean != null) {
            edtPhone.setText(userBean.getCell_num());
            edtMail.setText(userBean.getEmail());
            edtQq.setText(userBean.getQq());
            edtNickname.setText(userBean.getNickname());
            edtRealName.setText(userBean.getReal_name());
            edtOccupy.setText(userBean.getJob());
            edtCompanyName.setText(userBean.getCompany_name());
            edtCompanyType.setText(userBean.getCompany_type());
            edtAddress.setText(userBean.getAddress());
            edtFax.setText(userBean.getFax());
            edtZipCode.setText(userBean.getZip_code());

            if (userBean.getGender() == 0) {
                rg.check(R.id.rb_female);
            }

            if (!TextUtils.isEmpty(userBean.getPortrait_uri())) {
                Glide.with(this).load(userBean.getPortrait_uri()).into(imgSetHead);

            }

        } else {
//            toast("没有数据！");

            userBean = new UserBean();
            userBean.setId(SpUtils.getInstance().getUserId());


        }

    }


    public boolean saveInfo() {
        if (TextUtils.isEmpty(edtPhone.getText().toString().trim())) {
            toast("手机号不能为空");
            return false;
        } else if (TextUtils.isEmpty(edtMail.getText().toString().trim())) {
            toast("邮箱不能为空");
            return false;
        } else if (!CommonUtils.isEmail(edtMail.getText().toString().trim())) {
            toast("邮箱格式不正确");
            return false;
        }


        if (!TextUtils.isEmpty(edtPhone.getText().toString().trim())) {
            reqUserBean.setCell_num(edtPhone.getText().toString().trim());//手机号
            userBean.setCell_num(edtPhone.getText().toString().trim());
        }
        if (!TextUtils.isEmpty(edtMail.getText().toString().trim())) {
            reqUserBean.setEmail(edtMail.getText().toString().trim());
            userBean.setEmail(edtMail.getText().toString().trim());
        }//邮箱
        if (!TextUtils.isEmpty(edtQq.getText().toString().trim())) {
            reqUserBean.setQq(edtQq.getText().toString().trim());
            userBean.setQq(edtQq.getText().toString().trim());

        }//qq
        if (!TextUtils.isEmpty(edtRealName.getText().toString().trim())) {
            reqUserBean.setReal_name(edtRealName.getText().toString().trim());
            userBean.setReal_name(edtRealName.getText().toString().trim());
        }//真实姓名
        if (!TextUtils.isEmpty(qiNiuPicUrl)) {
            reqUserBean.setPortrait_uri(qiNiuPicUrl);
            userBean.setPortrait_uri(UrlHelper.SERVICE_IMAGE_BASE_URL + qiNiuPicUrl);
        }//头像
        if (!TextUtils.isEmpty(edtOccupy.getText().toString().trim())) {
            reqUserBean.setJob(edtOccupy.getText().toString().trim());
            userBean.setJob(edtOccupy.getText().toString().trim());
        }//职业
        if (!TextUtils.isEmpty(edtCompanyName.getText().toString().trim())) {
            reqUserBean.setCompany_name(edtCompanyName.getText().toString().trim());
            userBean.setCompany_name(edtCompanyName.getText().toString().trim());
        }//公司名称
        if (!TextUtils.isEmpty(edtCompanyType.getText().toString().trim())) {
            reqUserBean.setCompany_type(edtCompanyType.getText().toString().trim());
            userBean.setCompany_type(edtCompanyType.getText().toString().trim());
        }//公司类型
        if (!TextUtils.isEmpty(edtAddress.getText().toString().trim())) {
            reqUserBean.setAddress(edtAddress.getText().toString().trim());
            userBean.setAddress(edtAddress.getText().toString().trim());
        }//地址
        if (!TextUtils.isEmpty(edtFax.getText().toString().trim())) {
            reqUserBean.setFax(edtFax.getText().toString().trim());
            userBean.setFax(edtFax.getText().toString().trim());
        }//传真
        if (!TextUtils.isEmpty(edtZipCode.getText().toString().trim())) {
            reqUserBean.setZip_code(edtZipCode.getText().toString().trim());
            userBean.setZip_code(edtZipCode.getText().toString().trim());
        }//邮编

        reqUserBean.setGender(gender);//性别  0:女 1:男
        userBean.setGender(gender);
        return true;
    }


    @Override
    protected void initListener() {
        txtUploadHeadImg.setOnClickListener(this);
        txt_delete_headimg.setOnClickListener(this);
        txt_save.setOnClickListener(this);

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_male:
                        gender = 1;
                        break;
                    case R.id.rb_female:
                        gender = 0;
                        break;
                }

            }
        });

    }

    @Override
    protected void otherViewClick(View view) {
        switch (view.getId()) {
            case R.id.txt_upload_headimg:
                if (popwindow == null) {
                    popwindow = new CameraAlbumPopwindow(this, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            switch (view.getId()) {
                                case R.id.txt_camera:
                                    popwindow.dismiss();
                                    permissonCheck(PhotoUtils.REQUEST_CODE_CAMERA);
                                    break;
                                case R.id.txt_album:
                                    popwindow.dismiss();
                                    permissonCheck(PhotoUtils.REQUEST_CODE_ALBUM);
                                    break;

                                case R.id.txt_cancel:
                                    popwindow.dismiss();
                                    break;

                            }

                        }
                    });
                }
                popwindow.showAtLocation(view, Gravity.CENTER, 0, 0);


                break;
            case R.id.txt_delete_headimg:
                qiNiuPicUrl = "";
                imgSetHead.setImageDrawable(null);

                break;
            case R.id.txt_save:
                if (saveInfo()) {
                    showPg();
                    mPresenter.updateUser(reqUserBean);
                }


                break;

        }

    }


    @Override
    protected void initView() {
        btnLeft = rlLeft;
        mTitle = txtTitle;
        btRight = btnRight;
    }


    public boolean checkNull() {
        boolean isNull = false;
        if (edtPhone.getText().toString().trim().length() == 0) {
            toast("手机号不能为空");
            isNull = true;
            dismissPg();
        } else if (edtMail.getText().toString().trim().length() == 0) {
            toast("邮箱不能为空");
            isNull = true;
            dismissPg();
        } else if (!CommonUtils.isEmail(edtMail.getText().toString().trim())) {
            toast("邮箱格式错误");
            isNull = true;
            dismissPg();
        }
        return isNull;
    }


    //动态申请权限
    public void permissonCheck(int type) {
        //第二个参数是需要申请的权限
        switch (type) {
            case PhotoUtils.REQUEST_CODE_CAMERA:
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                        Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {   //权限还没有授予，需要在这里写申请权限的代码
                    // 第二个参数是一个字符串数组，里面是你需要申请的权限 可以设置申请多个权限
                    // 最后一个参数是标志你这次申请的权限，该常量在onRequestPermissionsResult中使用到
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                            type);

                } else {
                    initFile();
                    if (PhotoUtils.hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            //通过FileProvider创建一个content类型的Uri
                            imageUri = FileProvider.getUriForFile(this, CommonValue.PROVIDER_NAME, fileUri);
                        PhotoUtils.takePicture(this, imageUri, PhotoUtils.REQUEST_CODE_CAMERA);
                    } else {
                        Toast.makeText(this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
                        Log.e("asd", "设备没有SD卡");
                    }
                }
                break;

            case PhotoUtils.REQUEST_CODE_ALBUM:
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {   //权限还没有授予，需要在这里写申请权限的代码
                    // 第二个参数是一个字符串数组，里面是你需要申请的权限 可以设置申请多个权限
                    // 最后一个参数是标志你这次申请的权限，该常量在onRequestPermissionsResult中使用到
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            type);
                } else {
                    initFile();
                    PhotoUtils.openAlbum(this);
                }
                break;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == PhotoUtils.REQUEST_CODE_CAMERA) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                initFile();
                if (PhotoUtils.hasSdcard()) {
                    imageUri = Uri.fromFile(fileUri);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        //通过FileProvider创建一个content类型的Uri
                        imageUri = FileProvider.getUriForFile(this, CommonValue.PROVIDER_NAME, fileUri);
                    PhotoUtils.takePicture(this, imageUri, PhotoUtils.REQUEST_CODE_CAMERA);
                } else {
                    Toast.makeText(this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
                    Log.e("asd", "设备没有SD卡");
                }
            } else {
                toast("请在系统设置中开启权限");
            }
        } else if (requestCode == PhotoUtils.REQUEST_CODE_ALBUM) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                initFile();
                PhotoUtils.openAlbum(this);
            } else {
                toast("请在系统设置中开启权限");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    //初始化文件夹,不存在就创建
    public void initFile() {
        PhotoUtils.getSdCardFile();
        if (fileUri == null) {
            fileUri = new File(PhotoUtils.CAMERA_SAVE_PATH + "/photo.jpg");
        }
        if (fileCropUri == null) {
            fileCropUri = new File(PhotoUtils.CAMERA_SAVE_PATH + "/crop_photo.jpg");
        }
    }


    //当拍摄照片完成时会回调到onActivityResult 在这里处理照片的裁剪
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case PhotoUtils.REQUEST_CODE_CAMERA:
                cropImageUri = Uri.fromFile(fileCropUri);
                PhotoUtils.cropImageUri(this, imageUri, cropImageUri, PhotoUtils.REQUEST_CODE_CUT);

                break;

            case PhotoUtils.REQUEST_CODE_ALBUM:
                if (data == null || data.getData() == null) {
                    return;
                }
                if (PhotoUtils.hasSdcard()) {
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        newUri = FileProvider.getUriForFile(this, CommonValue.PROVIDER_NAME, new File(newUri.getPath()));
                    PhotoUtils.cropImageUri(this, newUri, cropImageUri, PhotoUtils.REQUEST_CODE_CUT);
                } else {
                    Toast.makeText(this, "设备没有SD卡!", Toast.LENGTH_SHORT).show();
                }

                break;

            case PhotoUtils.REQUEST_CODE_CUT:
                //图片裁切完成，显示裁切后的图片
                Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                if (bitmap != null) {
                    Glide.with(this).load(bitmap).into(imgSetHead);
                }
                showPg();
                qiNiuPicName = SpUtils.getInstance().getUserName() + "/" + "portrait_" + SpUtils.getInstance().getUserId() + "_" + System.currentTimeMillis() + ".jpg";
                mPresenter.upLoadImg(fileCropUri, qiNiuPicName);
//
////                /user_name/"portrait_"+id.jpg
//                QiniuUtil.getInstance().upLoadImg(fileCropUri, qiNiuName, SpUtils.getInstance().getImgToken());
                break;


        }


    }


    @Override
    public void upLoadImageSuccess(QiniuUploadImageBean bean) {
        dismissPg();
        qiNiuPicUrl = "/" + bean.getKey();
        Log.e("地址", qiNiuPicUrl);
    }

    @Override
    public void upLoadImageFail(String failMsg) {
        dismissPg();
        toast(failMsg);

    }

    @Override
    public void upDateUserSuccess() {

        userBeanUtil.updateUser(userBean);
        EventBus.getDefault().post(new LoginEvent(1));
        dismissPg();
        toast("保存成功");

    }

    @Override
    public void upDateUserFail(String failMsg) {
        dismissPg();
        toast(failMsg);
    }
}
